﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;

namespace SocketClient {
  /// <summary>
  /// MainWindow.xaml 的交互逻辑
  /// </summary>
  public partial class MainWindow: Window {
    public MainWindow() {
      InitializeComponent();
    }

    private Socket _send;
    private void Button_Click(object sender, RoutedEventArgs e) {
      try {
        // 创建一个负责通信的socket
        _send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ip = IPAddress.Parse(Ip.Text);
        IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(Port.Text));
        // 连接服务器

        _send.Connect(point);
        ShowMsg("连接成功");

        Thread th = new Thread(Receive);
        th.IsBackground = true;
        th.Start();
      } catch {
        // 
        MessageBox.Show("连接失败");
      }
    }
    // 显示消息
    private void ShowMsg(string info) {
      // 消除跨线程访问的错误
      ShowInfoBox.Dispatcher.Invoke(() => {
        ShowInfoBox.AppendText($"{info}\r\n");
      });
    }

    // 接收服务器发送过来的数据
    private void Receive() {
      while (true) {
        try {
          byte[] buffer = new byte[1024 * 1024 * 5];
          int count = _send.Receive(buffer);
          if (count == 0) break;

          var protocol = buffer[0];
          switch (protocol) {
            // 文本消息
            case 0:
              // 解码
              string str = Encoding.UTF8.GetString(buffer, 1, count - 1);
              ShowMsg($"{_send.RemoteEndPoint}: {str}");
              break;
            // 文件
            case 1:
              break;
            // 震动
            case 2:
              break;
            default:
              break;
          }
        } catch {
          // 
        }

      }
    }

    private void Button_Click_1(object sender, RoutedEventArgs e) {
      string str = SendInfoBox.Text.Trim();
      byte[] buffer = Encoding.UTF8.GetBytes(str);
      // 向服务器发送数据
      _send.Send(buffer);
      SendInfoBox.Text = "";
    }
  }
}
